<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户
 * @author www.dingwei.cn
 */
class Home extends MY_Controller {
	
	/**
	 * 广告模块
	 * @var AdmAdsModel
	 */
	public $mAds;
	
	/**
	 * 分类模块
	 * @var ConsumerCategoryModel
	 */
	public $mCategory;
	
	/**
	 * 分类模块
	 * @var AdmNewsModel
	 */
	public $mNew;
	
	/**
	 * 分类模块
	 * @var MerchantUserModel
	 */
	public $mShop;
	
	/**
	 * 设置模块
	 * @var AdmSettingModel
	 */
	public $mSetting;
	
	/**
	 * 银行模块
	 * @var AdmBankModel
	 */
	public $mBank;
	/**
	 * 模块
	 * @var ConsumerPromotionModel
	 */
	public $mPromotion;
	
	/**
	 * 位置标识
	 * @var array
	 */
	public $ADS_POSTION = [
        1 => 'home_top',//首页顶部
        3 => 'home_middle_left',//中间 左边
        4 => 'home_middle_right_top',//中间 右上
        5 => 'home_middle_right_down',//中间右下
	];
	
	/**
	 * 构造函数
	 */
	public function __construct(){
		parent::__construct();
		$this->loadModel('AdmAdsModel', 'mAds', 'admin');
		$this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
		$this->loadModel('AdmNewsModel', 'mNew', 'admin');
		$this->loadModel('MerchantUserModel', 'mShop', 'merchant');
		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$this->loadModel('AdmBankModel', 'mBank', 'admin');
	}

	/**
	 * 商城首页接口
	 * @desc 当首页界面功能 与 商盟界面功能一致时 可使用同一接口
	 */
    public function index(){

        $s = $this->getSessionId();
        if (!$s) {
//            wechat()->setHost('http://www.readyforgoing.com/gebi/wechat.php');
            $openid = wechat()->get_openid();
            // 验证用户是否存在， 不存在则跳转注册。 存在直接登录
            $id = $this->mUser->openidIsExist($openid);
            if ($id) {
                //设置sessionId
                $key = config_item('encryption_key');
                $sessionId = encryption($id.$key.time().mt_rand(10,100000));
                if(empty($sessionId)){
                    show_error('登录失败');
                }
                if($this->mUser->addSession($id, $sessionId, 2)){
                    $this->mUser->save(array('last_login_time'=>time(),'openid' => $openid),$id);
                    setcookie('wx_sessionid', encode($sessionId), 0, '/');
                    setcookie('wx_openid', encode($openid), 0, '/');
                }
            }else{
                if($openid){
                    setcookie('wx_openid', encode($openid), 0, '/');
                }

               //redirect(getUrl('user/login'));
            }
        }

        /**
         * 获取广告、轮播图
         * @var array $tAds
         */
        $tData = $this->mAds->getAdsList(array(1,2,3,4,5),0,2);

        /*
         * 获取分类 一级
         */
        $category = $this->mCategory->getCategoryList(0);

        $latitude 		= $this->latitude;
        $longitude 		= $this->longitude;

        //获取店铺
        $list = $this->mShop->appGetShopList(0,2,0, 1, array(),false,
            0, $latitude, $longitude,0);
        $c = $this->mCategory->getCategoryList(0);
        $i = 0;
        $shopCategory = array(
            array(
                'title' => '全部分类',
                'value' => 0,
            )
        );
        foreach ($c as $k => $v){
            $i++;
            $shopCategory[$i] = array(
                'title' => $v['cat_name'],
                'value' => $v['id'],
            );
        }
        unset($c);
        $sharp = $this->mSetting->get('sharp_title,sharp_icon,sharp_url,sharp_desc');
        $sharp['sharp_icon'] = getImage($sharp['sharp_icon'],'og');

        $data = array(
            'list' => $list,
            'shopCategory' => json_encode($shopCategory, JSON_UNESCAPED_UNICODE),
            'tData' => $tData,
            'category' => $category,
            'active' => 'home',
            'share' => json_encode($sharp, JSON_UNESCAPED_UNICODE),
            'title' => '戈壁市集',
            'reload' => isset($_GET['reload'])?1:2,
            'sign'=>wechat()->getSignPackage(),
        );
        
        $this->view('home/index', $data, 'layer_mobile');
    }

    /**
     * 商户列表
     */
    public function shop(){
        $categoryId 	= (int)get('category_id'); //分类
        if (!$categoryId){
            show_404();
        }
        //验证分类是否存在
        if ($categoryId){
            $categoryInfo = $this->mCategory->getInfo($categoryId);
            if ( ! $categoryInfo){
                show_error('分类不存在');
            }
        }
        $latitude 		= $this->latitude;
        $longitude 		= $this->longitude;

        //获取店铺
        $list = $this->mShop->appGetShopList($categoryId,2,0, 1, array(),false,
            0, $latitude, $longitude,0);
        $c = $this->mCategory->getCategoryList(0);
        $i = 0;
        $category = array(
            array(
                'title' => '全部分类',
                'value' => 0,
            )
        );
        foreach ($c as $k => $v){
            $i++;
            $category[$i] = array(
                'title' => $v['cat_name'],
                'value' => $v['id'],
            );
        }
        unset($c);
        $data = array(
            'categoryInfo' => $categoryInfo,
            'category' => json_encode($category, JSON_UNESCAPED_UNICODE),
            'list' => $list,
            'title' => '商户列表'
        );
        $this->view('home/shop', $data, 'layer_mobile');
    }

    /**
     * 获取店铺列表
     */
    public function getShopList(){
        //表单验证
        $vConf = array(
            array('sort', '排序类型', 'required|is_natural_no_zero'),
            array('category_id', '分类id', 'is_numeric'),
            array('page', '分页', 'required|is_natural_no_zero'),

        );
        $this->formDataValidation($vConf);


        $sort 			= (int)post('sort');	//排序规则 可选
        $categoryId 	= trim(post('category_id')); //分类
        $page 			= trim(post('page'));//分页
        $limit 			= trim(post('limit'));
        $keyword 		= trim(post('keyword'));
//        $latitude 		= trim(post('latitude'));
//        $longitude 		= trim(post('longitude'));
        $latitude 		= $this->latitude;
        $longitude 		= $this->longitude;

        if ( ! in_array($sort, array(1,2,3,4))){
            $this->appReturn(0,'排序错误');
        }

        //验证分类是否存在
        if ($categoryId){
            if ( ! $this->mCategory->getInfo($categoryId)){
                $this->appReturn(0,'分类不存在');
            }
        }

        //获取店铺
        $tShop = $this->mShop->appGetShopList($categoryId,$sort,0,$page,array(),false,$keyword,$latitude,$longitude,$limit);

        $this->appReturn(1,'',$tShop);
    }

	/**
	 * 获取商盟红包列表
	 */
	public function getBonusList(){
		$page = post('page');
		$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
		$tA = $this->mPromotion->homeGetBonusList($page);
		if ( ! $tA){
			$this->appReturn(1,'没有商盟红包');
		}
		$this->appReturn(1,'',$tA);
	}

	/**
	 * 获取分类列表
	 */
	public function getCategoryList(){
		
		$parentId = (int)post('parent_id');
		
		if ( ! is_numeric($parentId)){
			$this->appReturn(0,'数据类型int');
		}

		$tA = $this->mCategory->getCategoryList($parentId);
		if ( ! $tA){
			$this->appReturn(1,'没有任何分类');
		}
		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 获取分类列表
	 */
	public function getCustomCategoryList(){
		//表单验证
		$vConf = array(
		 	array('merchant_id', '商家id', 'required|is_natural_no_zero'),//1-首页 2-商盟
		 );
		 $this->formDataValidation($vConf);
		 
		$merchantId = (int)post('merchant_id');
		$parentId = (int)post('parent_id');
		
		if ( ! is_numeric($parentId)){
			$this->appReturn(0,'数据类型int');
		}

		$tA = $this->mCategory->getCustomList($merchantId,$parentId);
		
		if ( ! $tA){
			$this->appReturn(0,'数据不存在');
		}
		$recommend = array(
				'id'=>'recommend', //-死数据
				'cat_name'=>'推荐商品',
		);
		array_unshift($tA,$recommend);
		$this->appReturn(1,'',$tA);
	}

    /**
     * 获取地址
     */
    public function address(){

        $address = array();

        if($this->userId){
            $this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
            //获取收货地址
            $address = $this->mAddress->appGetList($this->userId, 0, true);
        }
        $data = array(
            'title' => '选择地址',
            'sign'=>wechat()->getSignPackage(),
            'address' => $address
        );
        $this->view('home/address', $data,'layer_mobile');
    }

    /**
     * 存经纬度
     */
    public function setLonLat(){
        //表单验证
        $vConf = array(
            array('latitude', '坐标', 'required'),
            array('longitude', '坐标', 'required'),
        );
        $type = trim(post('type'));
        if ($type != 'wgs84'){
            $vConf[] = array('address', '地址', 'required');
        }
        $this->formDataValidation($vConf);
        $latitude = trim(post('latitude'));
        $longitude = trim(post('longitude'));
        $address = trim(post('address'));
        if ($type == 'wgs84'){
            // 坐标转换
            $this->loadModel('AdmSettingModel', 'mSett', 'admin');
            $config = $this->mSett->get('map_key', 'deliveryman');
            $url = 'http://api.map.baidu.com/geoconv/v1/?coords='.$longitude.','.$latitude.'&from=1&to=5&ak='.$config;
            $lonLat = file_get_contents($url);
            $lonLat = json_decode($lonLat, true);
            if ($lonLat['status'] > 0){
                $this->ajaxReturn(0, '地址转换错误');
            }
            $latitude = $lonLat['result'][0]['y'];
            $longitude = $lonLat['result'][0]['x'];
            $aR = file_get_contents('http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='.$latitude.','.$longitude.'&output=json&pois=1&ak='.$config);
            $aR = ltrim($aR, 'renderReverse&&renderReverse(');
            $aR = rtrim($aR, ')');
            $aR = json_decode($aR, true);
            if ($aR['status'] > 0){
                $this->ajaxReturn(0, '坐标解析错误');
            }
            $address = $aR['result']['formatted_address'];
        }
        $coordinate = array(
            $latitude,
            $longitude,
            $address
        );
        $this->latitude = $latitude;
        $this->longitude = $longitude;
        $return = $coordinate;
        $coordinate = encode(json_encode($coordinate));
        setcookie('coordinate', $coordinate, time()+3600*24,'/');
        $this->ajaxReturn(1, '', $return, getUrl('home'));
    }

    /**
     * 搜索
     */
	public function search(){
        $search = array();
        if (!empty($_COOKIE['wx_search'])){
            $search = json_decode($_COOKIE['wx_search'], true);
        }
        $merchantId = (int)get('merchant_id');
        if ($this->userId == 2){
//            echo $merchantId;
        }
        $hot = $this->mSetting->get('hot_search');
        $data = array(
            'merchantId' => $merchantId ? $merchantId : 0,
            'search' => $search,
            'hot' => json_decode($hot),
            'title' => '搜索'
        );
        $this->view('home/search', $data, 'layer_mobile');
    }

    /**
     *  关键词搜索
     */
    public function searchByKeyword(){
        //表单验证
        $vConf = array(
            array('keyword', '关键词', 'required'),
        );
        $merchantId = post('merchant_id');
        if ($merchantId) {
            $vConf[] = array('merchant_id', '店铺id', 'is_natural_no_zero');
        }
        $this->formDataValidation($vConf);
        $keyword = trim(post('keyword'));
        $isSearch = trim(post('search'));

        $longitude = $this->longitude;
        $latitude = $this->latitude;
        if ($merchantId){
            //获取商品
            $tProduct = $this->mShop->searchProductByKeyword($keyword, $latitude, $longitude, $merchantId);
            $tShop = array();
        }else{
            //获取店铺
            $tShop = $this->mShop->searchShopByKeyword($keyword, $latitude, $longitude);
            //获取商品
            $tProduct = $this->mShop->searchProductByKeyword($keyword, $latitude, $longitude);
        }

        // 保存搜索
        if (!empty($_COOKIE['wx_search'])){
            $search = json_decode($_COOKIE['wx_search'], true);
        }else{
            $search = array();
        }
        if ($isSearch == 'false'){
            array_unshift($search, $keyword);
            $search = array_slice($search, 0, 10);
            $search = json_encode($search, JSON_UNESCAPED_UNICODE);
            setcookie('wx_search', $search, 0, '/');
        }
        $data = array(
            'search' => $search,
            'product' => $tProduct,
            'shop' => $tShop,
        );
        $this->appReturn(1, '', $data);
    }

    /**
     * 删除搜索记录记录
     */
    public function unSearch(){
        setcookie('wx_search', '', 0, '/');
        $this->ajaxReturn(1, '');
    }

	/**
	 * 获取地址
	 */
	public function getLocation(){
		//表单验证
		$vConf = array(
				array('parent_id', '上级id', 'required|is_natural_no_zero'),
				
		);
		$this->formDataValidation($vConf);
		
		$parentId = trim(post('parent_id'));
		
		$tA = $this->mSetting->getLocationByPid($parentId);
		
		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 获取开户行
	 */
	public function getBankList(){
		$tA = $this->mBank->getList();
		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 获取分享参数
	 */
	public function getSharp(){
		$tA = $this->mSetting->get('sharp_title,sharp_icon,sharp_url,sharp_desc');
		$tA['sharp_icon'] = getImage($tA['sharp_icon'],'og');
		//$tA['sharp_url'] = getUrl('app/home/share');
		$this->appReturn(1,'',$tA);
	}

	/**
	 * 分享下载页面
	 */
	public function share(){
		$tA = $this->mSetting->get('
									app_merchant_android_download_url, 
									app_consumer_android_download_url,
									app_consumer_ios_download_url,
									app_merchant_ios_download_url');
		$this->view('share/share',[
				'android_consumer'=>$tA['app_consumer_android_download_url'],
				'android_merchant'=>$tA['app_merchant_android_download_url'],
				'ios_consumer'=>$tA['app_consumer_ios_download_url'],
				'ios_merchant'=>$tA['app_merchant_ios_download_url'],
				]
		);
	}
	
    /**
     * 分享成功赠送积分
     * @author heyu
     */
    public function giftIntegral(){
        $this->loadModel('ConsumerExperienceValueModel', 'mExperience','consumer');
        $this->loadModel('ConsumerMallModel', 'mMall','consumer');
        $this->mMall->_addIntegral(5, $this->userId, $this->userIntegral);
        $this->mExperience->_addExperienceValue(4, $this->userId, $this->userExperienceValue);
        $this->ajaxReturn(1, '赠送成功');
    }




	/**
	 * 获取积分说明
	 */
	public function getIntegralDesc(){
		$info = $this->mSetting->getExplain('integral_desc');
		$this->appReturn(1,'',$info);
	}

	/**
	 * 获取红包描述
	 */
	public function getBonusDesc(){
		$info = $this->mSetting->getExplain('bonus_desc');
		$this->appReturn(1,'',$info);
	}
	
	/**
	 * 获取代金劵描述
	 */
	public function getCouponDesc(){
		$info = $this->mSetting->getExplain('coupon_desc');
		$this->appReturn(1,'',$info);
	}
	
	/**
	 * 获取提现说明
	 */
	public function getWithdrawDesc(){
		$info = $this->mSetting->getExplain('consumer_withdraw_desc');
		$this->appReturn(1,'',$info);
	}
	
	/**
	 * 获取充值说明
	 */
	public function getRechargeDesc(){
		$info = $this->mSetting->getExplain('recharge_desc');
		$this->appReturn(1,'',$info);
	}
	
	/**
	 * 获取申请售后原因
	 */
	public function getAftersaleReason(){
		$info = $this->mSetting->get('aftersale_reason');
		$this->appReturn(1,'',json_decode($info,true));
	}

	/**
	 * 获取店铺/配送员评论标签
	 */
	public function getCommentTags(){
		$m = $this->mSetting->get('merchant_comment_tags');
        $d = $this->mSetting->get('deliveryman_comment_tags', 'deliveryman');
		$data = array(
		    'merchant' => json_decode($m,true),
		    'deliveryman' => json_decode($d,true),
        );
		$this->appReturn(1,'', $data);
	}
	
	/**
	 * 平台获取基本信息
	 */
	public function getBase(){
		$info = $this->mSetting->get('web_service_tel,web_service_qq,hot_search');
		$this->appReturn(1,'',[
				'web_service_tel'=>$info['web_service_tel'],
				'web_service_qq'=>$info['web_service_qq'],
				'hot_search'=>json_decode($info['hot_search']),
		]);
	}
	
	public function test(){

	}
	
}